<template>
  <div class="max-w-4xl mx-auto p-6">
    <h1 class="text-2xl font-semibold">反转（Reverse）</h1>
    <p class="mt-4 text-gray-600">将文本按不同方式反转：按字符反转、按行倒序或全文反转。</p>

    <div class="mt-6 space-y-4">
      <div class="flex items-center space-x-3">
        <label class="text-sm text-gray-700">反转模式：</label>
        <select v-model="mode" class="border rounded px-2 py-1">
          <option value="chars">按字符（逐行内字符反转）</option>
          <option value="lines">按行倒序（行顺序翻转）</option>
          <option value="whole">全文反转（包含换行符）</option>
        </select>

        <label class="ml-4 flex items-center space-x-2 text-sm">
          <input type="checkbox" v-model="skipEmpty" class="form-checkbox" />
          <span>忽略空行（适用于按字符/按行模式）</span>
        </label>
      </div>

      <div class="flex space-x-4">
        <div class="flex-1">
          <div class="flex items-center justify-between mb-2">
            <label class="text-sm font-medium">输入</label>
            <div class="space-x-2">
              <button @click="pasteFromClipboard" class="text-sm text-blue-500">粘贴</button>
              <input ref="fileInput" type="file" accept=".txt" class="hidden" @change="onFileChange" />
              <button @click="() => $refs.fileInput.click()" class="text-sm text-blue-500">打开文件</button>
            </div>
          </div>
          <textarea v-model="inputText" rows="12" class="w-full border rounded p-2"></textarea>
        </div>

        <div class="flex-1">
          <div class="flex items-center justify-between mb-2">
            <label class="text-sm font-medium">输出</label>
            <div class="space-x-2">
              <button @click="copyOutput" class="text-sm text-blue-500">复制</button>
              <button @click="downloadOutput" class="text-sm text-blue-500">下载</button>
            </div>
          </div>
          <textarea :value="outputText" rows="12" readonly class="w-full border rounded p-2 bg-gray-50"></textarea>
        </div>
      </div>

      <div class="flex items-center space-x-3">
        <button @click="processNow" class="primary-button">立即反转</button>
        <button @click="clearAll" class="secondary-button">清空</button>
        <nuxt-link to="/text-tools" class="ml-auto text-sm text-blue-500">返回文本工具</nuxt-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useTools } from '~/composables/useTools'

const { copyToClipboard, downloadFile, readFile, debounce } = useTools()

const inputText = ref('')
const outputText = ref('')

const mode = ref('chars') // 'chars' | 'lines' | 'whole'
const skipEmpty = ref(true)

const fileInput = ref(null)

const reverseString = (s) => {
  // 使用扩展运算符处理 Unicode surrogate 对
  return [...s].reverse().join('')
}

const processNow = () => {
  const raw = inputText.value || ''

  if (mode.value === 'whole') {
    outputText.value = reverseString(raw)
    return
  }

  // 按行处理
  let lines = raw.split(/\r?\n/)

  if (skipEmpty.value) {
    lines = lines.filter(l => l.trim().length > 0)
  }

  if (mode.value === 'lines') {
    lines = lines.slice().reverse()
    outputText.value = lines.join('\n')
    return
  }

  // 默认按字符反转（逐行）
  const processed = lines.map(l => reverseString(l))
  outputText.value = processed.join('\n')
}

const debouncedProcess = debounce(processNow, 250)

watch([inputText, mode, skipEmpty], () => {
  debouncedProcess()
})

const copyOutput = async () => {
  if (!outputText.value) return
  await copyToClipboard(outputText.value)
}

const downloadOutput = () => {
  if (!outputText.value) return
  downloadFile(outputText.value, 'reversed.txt')
}

const pasteFromClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText()
    inputText.value = text
  } catch (e) {
    console.error('读取剪贴板失败', e)
  }
}

const onFileChange = async (e) => {
  const file = e.target.files && e.target.files[0]
  if (!file) return
  try {
    const content = await readFile(file)
    inputText.value = content
  } catch (err) {
    console.error('读取文件失败', err)
  } finally {
    e.target.value = ''
  }
}

const clearAll = () => {
  inputText.value = ''
  outputText.value = ''
}

onMounted(() => {
  processNow()
})
</script>

